package fr.sedoo.commons.client.news.ui.table;

import java.util.Date;
import java.util.ListIterator;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.cellview.client.TextColumn;

import fr.sedoo.commons.client.message.CommonMessages;
import fr.sedoo.commons.client.news.bundle.NewsMessages;
import fr.sedoo.commons.client.news.ui.MessageManageView.Presenter;
import fr.sedoo.commons.client.util.DateUtil;
import fr.sedoo.commons.client.util.LocaleUtil;
import fr.sedoo.commons.client.widget.table.AbstractListTable;
import fr.sedoo.commons.shared.domain.HasIdentifier;
import fr.sedoo.commons.shared.domain.message.MessageTableItem;


public class MessageTable extends AbstractListTable {

	private Presenter presenter;

	@Override
	public void presenterEdit(HasIdentifier hasIdentifier) 
	{
		presenter.edit(((MessageTableItem)hasIdentifier).getUuid());
	}
		
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	
protected void initColumns() {
		
		TextColumn<HasIdentifier> titleColumn = new TextColumn<HasIdentifier>() {
			@Override
			public String getValue(HasIdentifier aux) 
			{
				return ((MessageTableItem) aux).getTitle();
			}
		};
		
		TextColumn<HasIdentifier> authorColumn = new TextColumn<HasIdentifier>() {
			@Override
			public String getValue(HasIdentifier aux) 
			{
				return ((MessageTableItem) aux).getAuthor();
			}
		};
		
		TextColumn<HasIdentifier> dateColumn = new TextColumn<HasIdentifier>() {
			@Override
			public String getValue(HasIdentifier aux) 
			{
				Date date = ((MessageTableItem) aux).getDate();
				return DateUtil.getDateByLocale(date, LocaleUtil.getClientLocaleLanguage(presenter.getClientFactory().getDefaultLanguage()));
			}
		};
		
		itemTable.addColumn(titleColumn, NewsMessages.INSTANCE.title());
		itemTable.setColumnWidth(titleColumn, 100.0, Unit.PX);
		
		itemTable.addColumn(authorColumn, NewsMessages.INSTANCE.author());
		itemTable.setColumnWidth(authorColumn, 80.0, Unit.PX);
		
		itemTable.addColumn(dateColumn, CommonMessages.INSTANCE.date());
		itemTable.setColumnWidth(dateColumn, 60.0, Unit.PX);
		
		itemTable.addColumn(editColumn);
		itemTable.setColumnWidth(editColumn, 30.0, Unit.PX);
		
		itemTable.addColumn(deleteColumn);
		itemTable.setColumnWidth(deleteColumn, 30.0, Unit.PX);
		
	}

	
		
	@Override
	public void presenterDelete(HasIdentifier hasId) {
		presenter.delete(((MessageTableItem) hasId).getUuid());
	}

	@Override
	public void addItem() {
		presenter.create();
	}

	@Override
	public String getAddItemText() {
		return NewsMessages.INSTANCE.addItemText();
	}

	public void broadcastDeletion(String uuid) {
		
		ListIterator<MessageTableItem> listIterator = (ListIterator<MessageTableItem>) model.listIterator();
		while (listIterator.hasNext()) {
			MessageTableItem item = listIterator.next();
			if (item.getUuid().compareTo(uuid) == 0) {
				listIterator.remove();
				break;
			}
		}
		init(model);
		
	}

}
